package com.example.template.controller;

import com.example.template.dao.AccountRepository;
import com.example.template.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.concurrent.TimeUnit;

/**
 * @author bueryouth
 * @date 2021/08/26
 */
@Slf4j
@Controller
public class LoginController {
    // protected static final Logger logger = LoggerFactory.getLogger(LoginControl.class);
    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/login")
    public ModelAndView login(ModelAndView mv) {
        mv.setViewName("login");
        return mv;
    }

    /**
     * 用户登录
     */
    @PostMapping("/userLogin")
    public ModelAndView userLogin(ModelAndView mv, Model model, @RequestParam(value = "userEmail") String userEmail,
        @RequestParam(value = "passWord") String passWord) {
        log.info(userEmail + "->" + passWord);
        Account user = accountRepository.findByUseremailAndPassword(userEmail, passWord);
        log.info("验证用户名->" + user.getUsername());
        String token = RandomStringUtils.randomAlphanumeric(10);
        // 存储Redis,并设置有效时间(过期单位自定义)
        stringRedisTemplate.opsForValue().set(token, user.getUserid(), 60, TimeUnit.SECONDS);
        log.info("随机生成token->" + token + "->" + "id->" + stringRedisTemplate.opsForValue().get(token));
        System.out.println(stringRedisTemplate.getExpire(token, TimeUnit.SECONDS));
        model.addAttribute("username", user.getUsername());
        model.addAttribute("token", token);
        mv.setViewName("home");
        return mv;
    }

    /**
     * 退出登录
     */
    @GetMapping("/exit")
    public ModelAndView exit(ModelAndView mv, @RequestParam("token") String token) {
        log.info("随机生成token->" + token + "->" + "id->" + stringRedisTemplate.opsForValue().get(token));
        mv.setViewName("login");
        stringRedisTemplate.delete(token);
        return mv;
    }
}